<?php

namespace app\common\model;

use think\Cache;

/**
 * 档案备注 模型
 * Class DivinationNote
 * @package app\common\model
 */
class RecodeNote extends Base
{
    /**
     * 档案备注的所有id
     */
    const REDIS_KEY_IDS = 'recode_note_ids_';
    /**
     * 档案备注的详情
     */
    const REDIS_KEY_DETAIL = 'recode_note_detail_';

    protected $table = 'wechat_backup_07_18_14_43_00.app_recode_note';
    protected $readonly = ['uid', 'did'];
    protected $insert = ['create_time', 'last_time'];
    protected $update = ['last_time'];


    public function del($id)
    {
        $detail = Cache::get(self::REDIS_KEY_DETAIL . $id);
        if ($detail != false && $detail['rid'])
        {
            Cache::rm(self::REDIS_KEY_IDS . $detail['rid']);
        }
        Cache::rm(self::REDIS_KEY_DETAIL . $id);

    }

    /**
     * 获取所有的数量
     * @param array $map
     * @return int
     */
    public function getCountAll($map = [])
    {
        //获取所有的ids
        return count($this->getList($map));
    }


    /**
     * 获取列表（注意备注没有分页）
     * @param array $map
     * @return array|bool|false|mixed|\PDOStatement|string|\think\Collection
     */
    public function getListAll($map = [], $version = 0)
    {

        return (new \app\common\cachemodel\RecodeNote())->getNoteListFromCache($map['uid'], $map['rid']);

        //获取所有的ids
        $recode_notes = $this->getList($map);
        if (count($recode_notes) == 0)
        {//如果ids为空，那么直接返回
            return $recode_notes;
        }
        if ($version > 0)
        {
            $per_page = 10;
            $data_list = getPaginatorData(count($recode_notes), $map['page'], $per_page);
            //获取分页后的数据
            $recode_notes = array_slice($recode_notes, $data_list['start'], $per_page);
            $data_list['data'] = $this->getDetails($recode_notes, $version);
            unset($data_list['start']);
            unset($data_list['end']);
        } else
        {
            $data_list = $this->getDetails($recode_notes, $version);
        }
        return $data_list;
    }


    /**
     * 获取详情
     * @param array $all_list
     * @return array|false|mixed|\PDOStatement|string|\think\Collection
     */
    public function getDetails($all_list = [], $version)
    {
        $result = [];
        $ids = $this->getAllNotCachedIds($all_list, self::REDIS_KEY_DETAIL);

        try
        {
            if (strlen($ids) > 0)
            {
                $where = 'id in(' . $ids . ')';
                $result = $this->field('*')
                    ->where($where)
                    ->order('id DESC')
                    ->select();
                $result = json_decode(json_encode($result, true), true);
                if ($this->cache_on >= 1)
                    foreach ($result as $v)
                        Cache::set(self::REDIS_KEY_DETAIL . $v['id'], $v, $this->cache_time);
            }
            if ($this->cache_on >= 1)//如果缓存打开，循环获取，因为缓存里已经有了数据
            {
                $result = [];
                foreach ($all_list as $v)
                {
                    $arr = Cache::get(self::REDIS_KEY_DETAIL . $v['id']);
                    if ($version > 0)
                    {
                        $arr['create_time'] = date('Y.m.d H:i', $arr['create_time']);
                        $arr['last_time'] = date('Y.m.d H:i', $arr['last_time']);
                        $arr['event_time'] = $arr['event_time'] ? date('Y.m.d H:i', $arr['event_time']) : '';
                    }
                    $result[] = $arr;
                }
            }
        }
        catch (\Exception $e)
        {
            // 错误信息写入日志
            \think\Log::write('获取星盘备注错误:' . '[' . $ids . ']', 'error', true);
        }
        return $result;
    }

    /**
     * 获取所有的ids
     * @param array $map
     * @return bool|false|mixed|\PDOStatement|string|\think\Collection
     */
    private function getList($map = [])
    {
        //获取 用户所有提问的id
        $recode_notes = false;
        if ($this->cache_on >= 1)
        {
            $recode_notes = Cache::get(self::REDIS_KEY_IDS . $map['rid']);
        }
        if ($recode_notes === false)
        {
            try
            {
                $recode_notes = $this
                    ->field('id')
                    ->where(['rid' => $map['rid'], 'uid' => $map['uid']])
                    ->order('create_time DESC')
                    ->select();
            }
            catch (\Exception $e)
            {
                // 错误信息写入日志
                \think\Log::write('获取星盘备注ids错误:' . '[' . $map['rid'] . ']', 'error', true);
            }
            //获取数据
            $recode_notes = json_decode(json_encode($recode_notes, true), true);

            //存储所有ids
            $cache_data = '';
            foreach ($recode_notes as $k => $v)
            {
                $cache_data .= ',' . $v['id'];
            }
            if ($this->cache_on >= 1)
            {
                Cache::set(self::REDIS_KEY_IDS . $map['rid'], $recode_notes, $this->cache_time);
            }
        }

        return $recode_notes;
    }
}
